package org.javamap.overlays;

import org.javamap.*;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;

import java.awt.geom.GeneralPath;

public class Trail extends LineOverlay
{
	public Trail(){ setName("unnamed trail"); }

	protected void drawOneLocation(Graphics2D g2d, Point p)
	{
		g2d.translate(p.x, p.y);
		g2d.draw(TRAIL_MARK);
	}

	protected void drawLineSegment(Graphics2D g2d, Point oldP, Point p)
	{
		java.awt.geom.AffineTransform originalTransform = g2d.getTransform();

		// Determine angle of line segment to rotate trail markers:
		double theta = Math.atan2(p.y - oldP.y, p.x - oldP.x);
		
		// Draw one trail marker per X pixels, leaving room for one at end.		
		double dist = p.distance(oldP);
		int n = (int) (dist / PIXELS_BETWEEN_MARKS);  // max number of marks
		double space = dist / n;
		
		g2d.translate(oldP.x, oldP.y);
		
		if (getLocationIndex() > 1) {
			// rotate an intermediate amount between the last rotation and
			//  this one:
			double intermRot;
			if (theta - lastTheta > Math.PI)
				intermRot = (theta + 2 * Math.PI + lastTheta) / 2.0;
			else intermRot = (theta + lastTheta) / 2.0;
			g2d.rotate(intermRot);
			g2d.draw(TRAIL_MARK);
			g2d.rotate(-intermRot);
			g2d.rotate(theta);
		} else {
			g2d.rotate(theta);
			g2d.draw(TRAIL_MARK);
		}

		lastTheta = theta;
		
		for (int ii = 1; ii < n; ++ii) {
			g2d.translate(space, 0.0);
			g2d.draw(TRAIL_MARK);
		}
		/*
		while (dist > PIXELS_BETWEEN_MARKS * 1.2) {
			dist -= PIXELS_BETWEEN_MARKS;
		
			g2d.draw(TRAIL_MARK);
			g2d.translate((double) PIXELS_BETWEEN_MARKS, 0.0);
		} */
		// Draw the last one, if and only if this is the last location:
		if (getLocationIndex() == getLocationCount() - 1) {
			g2d.translate(space, 0.0);
			g2d.draw(TRAIL_MARK);
		}

		g2d.setTransform(originalTransform);	
	}
	
	protected void setupForDraw(Graphics2D g2d)
	{
		g2d.setColor(COLOR_TRAIL);	
		g2d.setStroke(STROKE_TRAIL);
	}		
	
	private transient double lastTheta;
	
	private final static GeneralPath TRAIL_MARK = new GeneralPath();
	
	static {
		final int LEN = 3;  // length per arm of X, / sqrt(2)
		TRAIL_MARK.moveTo(-LEN, -LEN);
		TRAIL_MARK.lineTo(LEN, LEN);
		
		TRAIL_MARK.moveTo(-LEN, LEN);
		TRAIL_MARK.lineTo(LEN, -LEN);
	}
		
	private final static BasicStroke STROKE_TRAIL = new BasicStroke(
			1.5f,
			BasicStroke.CAP_SQUARE,
			BasicStroke.JOIN_MITER
	);
	private final static Color COLOR_TRAIL = Color.BLACK;
	private final static int PIXELS_BETWEEN_MARKS = 10;
}

